package cn.texous.web.parsing.book.context;

import cn.texous.util.commons.exception.BusinessException;
import cn.texous.web.parsing.book.common.constants.AnaResultCode;
import cn.texous.web.parsing.book.model.parser.origin.AnaOriginParser;
import cn.texous.web.parsing.book.service.api.mysql.AnaOriginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/**
 * insert description here
 *
 * @author Showa.L
 * @since 2019/7/25 16:54
 */
@Slf4j
@Component
public class OriginParserContext {

    private static final ConcurrentHashMap<String, AnaOriginParser>
            ORIGIN_PARSER_CONCURRENT_HASH_MAP = new ConcurrentHashMap<>();

    @Autowired
    private AnaOriginService anaOriginService;

    @PostConstruct
    public void init() {
        List<AnaOriginParser> anaOriginParsers = anaOriginService.buildOrigin();
        ORIGIN_PARSER_CONCURRENT_HASH_MAP.clear();
        anaOriginParsers.forEach(p -> ORIGIN_PARSER_CONCURRENT_HASH_MAP.put(p.getOrigin(), p));
    }

    /**
     * fiction format loader
     *
     * @param code code
     * @return
     */
    public AnaOriginParser loadByCode(String code) {
        return Optional
                .ofNullable(ORIGIN_PARSER_CONCURRENT_HASH_MAP.get(code))
                .orElseThrow(() -> new BusinessException(
                        AnaResultCode.FS_ORIGIN_UNSUPPORT_ERROR));
    }

}
